import Fields from "./lib/Fields";
import { getCurrentLngLat, getLocationByIp, inverseGeocoding } from "./lib/gps"; 

const file_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
    var data = new FormData();
    data.append('upload', blobInfo.blob());
    $.ajax({
        url: QEditor.option.upload_url,
        type: 'POST',
        data: data,
        dataType: 'json',
        processData: false,
        contentType: false,
        async: false,
        success: function (data) {
            if (data.code == 200) {
                resolve(data.data.path);
            } else {
                reject(data.msg);
            }
        }
    });
});


const JS_URL = document.currentScript.src;

window.QEditor = {

    url() {
        let Url_Info = this.parseURL(JS_URL),
            _dirs_ = Url_Info['segments'].slice(0, -3);
        return Url_Info.protocol + '://' + Url_Info.host +
            (Url_Info.port ? ':' + Url_Info.port : '') +
            '/' + (_dirs_.join('/')) + '/';
    },
    option: {
        api_url: '',
        upload_url: '?qeditor=upload',
        save_url: '?qeditor=save',
        relation_url: '?qeditor=relation',
        save_callback: ''
    },
    mini_field: '',
    env(callback) {
        let _this = this;
        this.require(['weui', 'jQuery'], () => {

            if (!$('.QEditor-css').length) {
                $('head').append('<link rel="stylesheet" class="QEditor-css" href="' + this.url() + 'static/css/form.css">');

                //这里是迷你字段的操作
                $(document).on('click', '.qedit-mini-field', (e) => {
                    var field = $(e.currentTarget).data('field'),
                        method = (typeof Fields[this.field_options[field].type] == "undefined") ? 'text' : this.field_options[field].type,
                        html = Fields[method](this.table, field, this.field_options[field], this.field_titles, this.QE_DATA, this.option, this.QE_RELATION, false);
                    _this.mini_field = _this.attr_field = field;
                    _this.attr_has_save = false;
                    console.log('_this.mini_field', _this.mini_field, html)
                    $('.show_picker_dialog .weui-half-screen-dialog__title').text(this.field_titles[field]);

                    if (method == 'area') {
                        _this.dialogArea(field);
                    } else {
                        $('#dialog-attr-content').html(html);
                    }

                    _this.show_not_picker();

                })
            }

            _this.isCallback(callback) && callback();

        });
    },

    field_titles: {},
    field_options: {},
    mini_fields: [],
    edit_fields: [],
    pk: '',
    QE_DATA: {},
    QE_RELATION: {},
    table: '',
    mode: 'user',

    dialogEdit(table, mode, id, target, option, _params_, save_callback) {
        let _this = this;
        this.require('jQuery', () => {

            if ($('#QEditor-dialog').length < 1) {
                $('body').append('<div id="QEditor-dialog"><div class="QEditor-mask"></div><div id="QEditor-dialog-content"></div></div>');
            }

            $('#QEditor-dialog-content').html('');

            _this.edit(table, mode, '#QEditor-dialog-content', id, option, _params_, save_callback);

            $('#QEditor-dialog').show();
        })

    },

    diy(target, save_url, fields_data, field_titles, field_options) {
        let _this = this;
        this.option.save_url = save_url;


        this.env(() => {
            //对象数据转换键值对
            _this.QE_DATA = Object.fromEntries(Object.entries(fields_data).map(([key, value]) => [key, value.value || '']));
            //获取field_titles所有key
            _this.edit_fields = Object.keys(field_titles);
            _this.field_titles = field_titles;
            _this.field_options = field_options;

            console.log(_this.field_options);
            _this.initObject();
            _this.initDom(target);

        })
    },
    edit(table, mode, target, id, option, _params_, save_callback) {

        if (typeof window.QEDITOR__CONF == "undefined") {
            require('../../static/config')
        }

        let _this = this;
        this.table = table;
        this.mode = mode;
        option && Object.assign(this.option, option);

        this.env(() => {
            // 获取数据库配置
            this.ajax('?qeditor=form', { table: table, pk_val: id, mode: this.mode, params: _params_ }, function (res) {

                if (typeof res.data.data != "undefined") {
                    _this.QE_DATA = res.data.data;
                    _this.QE_RELATION = res.data.relation || {};
                }

                if (typeof res.data.field_options != "undefined") {
                    _this.field_titles = res.data.field_titles;
                    _this.field_options = res.data.field_options;
                    _this.mini_fields = res.data.mini_fields || [];
                    _this.edit_fields = res.data.edit_fields;
                    _this.pk = res.data.pk;
                    _this.initObject();
                    _this.initDom(target);
                } else {
                    return _this.msg('初始化失败,请先配置表单', 'error');
                }

            })

            $(document).on('input propertychange', '#picker-search', (e) => {
                QEditor.picker_key = $(e.currentTarget).val();
                _this.getSelect();
            })

            $(document).on('click', '.QEditor-mask', (e) => {
                $('#QEditor-dialog').hide();
            })

        });
    },

    imageExtensions: ['jpg', 'jpeg', 'gif', 'png'],
    audioExtensions: ['mp3', 'wav'],
    renderFiles(field, rt) {
        //单文件
        let files = this.QE_DATA[field], html_file = '';


        if (this.QE_DATA[field] && typeof this.QE_DATA[field] == "string") {
            files = [{ path: files }];
        }


        if (!files) {
            $('#field-' + field + '-files').html('');
            return '';
        }

        for (var i in files) {
            var is_image = false, exts = ['.png', '.jpg', '.jpeg', '.gif'],
                url = files[i]['path'] || files[i]['url'] || files[i];

            if (url) {
                url = url.toString();
                var extension = url.split('.').pop().toLowerCase();
                if (this.imageExtensions.includes(extension)) {
                    is_image = true;
                }
            }

            html_file +=
                '<li class="weui-uploader__file" onclick="QEditor.fileOption(\'' + field + '\',' + i + ')" style="background-image: url(' + (is_image ? url : QEDITOR__CONF.FILE_ICON) + ');">' +
                '<i onclick="QEditor.delFile(this,\'' + field + '\',\'' + i + '\')">X</i><span class="uploader-name" style="' + (files[i].name ? '' : 'display:none') + '">' + (files[i].name || '') + '</span><span class="uploader-name" style="' + (files[i].price ? '' : 'display:none') + '">￥' + (files[i].price || '') + '</span></li>';
        }


        if (rt) {
            return html_file;
        }

        $('#field-' + field + '-files').html(html_file);
    },

    renderAttrs(field_name, rt) {

        var html = '', type = this.field_options[field_name].type, option = this.field_options[field_name].option_value,
            value = this.QE_DATA[field_name], is_single = typeof option.single == "undefined" ? 0 : 1;


        if (!value) {
            this.QE_DATA[field_name] = value = [];
        }

        if (is_single && JSON.stringify(value).indexOf('{') === 0) {
            value = [value];
        }

        var attrs = typeof option.attrs != "undefined" ? option.attrs : false;


        for (var i in value) {

            if (JSON.stringify(value[i]) == '{}') continue;

            html += '<div class="qedit-attr-item ' + (is_single ? 'attr-single' : '') + '" onclick="QEditor.editAttr(\'' + field_name + '\',' + i + ')">';
            if (attrs) {
                for (var k in attrs) {
                    html += `<p><span class="qedit-attr-label">` + attrs[k] + ` : </span><span class="qedit-attr-value">` + value[i][k] + `</span></p>`;
                }
            } else {
                for (var k in value[i]) {
                    html += `<p><span class="qedit-attr-label">` + k + ` : </span><span class="qedit-attr-value">` + value[i][k] + `</span></p>`;
                }
            }
            html += '<sup onclick="QEditor.deleteAttr(\'' + field_name + '\',' + i + ')">X</sup></div>';

        }

        if (rt) {
            return html;
        }

        $('#field-' + field_name + '-options').html(html);
    },
    deleteAttr(field_name, index) {
        event.stopPropagation();
        event.preventDefault();

        var option = this.field_options[field_name].option_value,
            is_single = typeof option.single == "undefined" ? 0 : 1;

        if (is_single) {
            this.QE_DATA[field_name] = {};
        } else {
            this.QE_DATA[field_name].splice(index, 1);
        }

        this.renderAttrs(field_name);
    },
    editAttr(field_name, index) {
        $('#piker-dialog,[data-show="!is_picker"]').show();
        $('[data-show="is_picker"]').hide();

        var html = '', type = this.field_options[field_name].type,
            option = this.field_options[field_name].option_value,
            is_single = typeof option.single == "undefined" ? 0 : 1,
            value = typeof index != "undefined" ? (is_single ? this.QE_DATA[field_name] : this.QE_DATA[field_name][index]) : {},
            attrs = typeof option.attrs != "undefined" ? option.attrs : false;
        console.log(field_name, 'value', value)

        this.attr = {};
        if (attrs) {
            let j = 0;
            for (var k in attrs) {
                // html += `<p><span class="qedit-attr-label">` + attrs[k] + ` : </span><span class="qedit-attr-value">` + k + `</span></p>`;
                if (typeof this.attr[k] == "undefined") {
                    this.attr[k] = (typeof value[k] == "undefined" ? '' : value[k]);
                }
                html += `<p class="qedit-attr"><input class="qedit-attr-input" name="attr_key_` + j + `" type="hidden" value="` + k + `" ><input class="qedit-attr-input"   type="text" value="` + attrs[k] + `" readonly> : <input onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)"  class="qedit-attr-input" name="attr_value_` + j + `" type="text" value="` + this.attr[k] + `"></p>`;
                j++;
            }
        } else if (typeof option.number != "undefined") {
            var number = parseInt(option.number);

            if (JSON.stringify(value) == "{}") {
                for (var i = 0; i < number; i++) {
                    if (typeof this.attr[i] == "undefined") {
                        this.attr[i] = '';
                    }
                    html += `<p class="qedit-attr"><input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)"  class="qedit-attr-input" name="attr_key_` + i + `" type="text" value="" > : <input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)"  class="qedit-attr-input" name="attr_value_` + i + `" type="text" value="` + this.attr[i] + `"></p>`;
                }
            } else {
                var i = 0;
                for (var k in value) {
                    if (typeof this.attr[k] == "undefined") {
                        this.attr[k] = (typeof value[k] == "undefined" ? '' : value[k]);
                    }
                    html += `<p class="qedit-attr"><input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)"  class="qedit-attr-input" name="attr_key_` + i + `" type="text" value="` + k + `" > : <input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)" name="attr_value_` + i + `"  class="qedit-attr-input" type="text" value="` + this.attr[k] + `"></p>`;
                    i++;
                }

                for (var j = i; j < option.number; j++) {
                    html += `<p class="qedit-attr"><input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)"  class="qedit-attr-input" name="attr_key_` + j + `" type="text" value="" > : <input  onchange="QEditor.saveAttrValue('` + field_name + `',` + index + `)" name="attr_value_` + j + `"  class="qedit-attr-input" type="text" value=""></p>`;
                }
            }

        }

        $('#dialog-attr-content').html(html);
    },
    saveAttrValue(field_name, index) {
        this.attr_field = field_name;
        this.attr_index = index;

        var attr_form = $('.qedit-attr-input').serializeArray(), keys = {}, values = {}, attr = {};

        for (var i in attr_form) {
            var k_attr = attr_form[i]['name'].split('_');

            if (k_attr[1] == 'key' && attr_form[i]['value']) {
                keys[k_attr[2]] = attr_form[i]['value'];
            }

            if (k_attr[1] == 'value' && attr_form[i]['value']) {
                values[k_attr[2]] = attr_form[i]['value'];
            }

        }

        for (var i in keys) {
            attr[keys[i]] = (typeof values[i] == "undefined") ? '' : values[i];
        }
        this.attr = attr;
        this.attr_has_save = false;

    },
    attr_field: '',
    attr_index: 0,
    attr_has_save: true,
    renderAreas(field) {

        if (!this.QE_DATA[field]) {
            return '';
        }
        this.ajax('?qeditor=areaValue', { area: this.QE_DATA[field] }, (res) => {
            var html = '';
            if (res.data) {

                for (var i in res.data) {
                    html += '<span class="qeditor-area-item" >' + res.data[i].name + '<sup onclick="QEditor.deleteAreaItem(\'' + field + '\',\'' + res.data[i].code + '\')">X</sup></span>'
                }
            }

            $('#field-' + field + '-areas').html(html);
        })

        return '';
    },
    deleteAreaItem(field, index) {
        this.QE_DATA[field].splice(this.QE_DATA[field].indexOf(index), 1);
        this.renderAreas(field);
    },
    hidePickerDialog() {

        $('#piker-dialog').hide();
        let _this = this;

        if (!this.attr_has_save) {

            //mini选择编辑保存
            if (this.attr_field == this.mini_field) {

                if (this.field_options[this.attr_field].type == 'area') {
                    this.QE_DATA[this.mini_field] = this.area_code;
                }

                this.miniValue(this.mini_field, true);
                this.mini_field = this.attr_field = '';
                this.attr_has_save = true;
                return true;
            }

            //区域特殊保存
            if (["area", "multiArea"].indexOf(this.field_options[this.attr_field].type) > -1) {

                if (this.field_options[this.attr_field].type === "multiArea") {
                    this.ajax('?qeditor=sonAreas', { area: this.area_code }, (res) => {

                        if (typeof this.QE_DATA[this.attr_field] == "string") {
                            _this.QE_DATA[_this.attr_field] = _this.QE_DATA[_this.attr_field].split(',');
                        }

                        if (res.data.length > 0) {
                            for (var i in res.data) {
                                if (_this.QE_DATA[_this.attr_field].indexOf(res.data[i].toString()) < 0) {
                                    _this.QE_DATA[_this.attr_field].push(res.data[i].toString());
                                }
                            }

                        } else if (_this.QE_DATA[_this.attr_field].indexOf(_this.area_code.toString()) < 0) {
                            _this.QE_DATA[_this.attr_field].push(_this.area_code.toString());
                        }

                        _this.renderAreas(_this.attr_field);
                        _this.attr_field = '';
                        _this.attr_has_save = true;

                    })


                } else {
                    this.QE_DATA[this.attr_field] = this.area_code;
                    this.miniValue(this.attr_field);
                    this.attr_field = '';
                    this.attr_has_save = true;
                }


                return true;
            }


            var is_single = typeof this.field_options[this.attr_field]['option_value'].single == "undefined" ? 0 : 1;

            if (is_single) {
                this.QE_DATA[this.attr_field] = this.attr;
            } else {
                if (typeof this.attr_index == "undefined") {
                    this.QE_DATA[this.attr_field].push(this.attr);
                } else {
                    this.QE_DATA[this.attr_field][this.attr_index] = this.attr;
                }
            }

            this.renderAttrs(this.attr_field);
            this.attr_has_save = true;
            console.log('属性编辑结果', this.QE_DATA[this.attr_field], this.attr_index)
        }
    },
    attr: {},
    saveAttr(e, field, key, index) {
        var index = parseInt(index)

        this.attr[key] = e.value;
        this.QE_DATA[field][index] = this.attr;
        this.renderFiles(field);
    },
    fileOption(field, index) {
        var type = this.field_options[field].type, option = this.field_options[field].option_value,
            index = parseInt(index);

        if ('attr_files' != type) return false;
        this.is_picker = false;

        this.show_not_picker();

        this.attr = this.QE_DATA[field][index];

        var html = `<p><span class="label">名称 : </span><span><input value="` + (QEditor.QE_DATA[field][index].name || '') + `"  type="text" onchange="QEditor.saveAttr(this,'` + field + `','name','` + index + `')"></span></p>`;

        for (var k in option) {
            if (typeof this.attr[k] == "undefined") {
                this.attr[k] = '';
            }

            html += `<p><span class="label">` + option[k] + ` : </span><span><input onchange="QEditor.saveAttr(this,'` + field + `','` + k + `','` + index + `')" value="` + (this.attr[k] || '') + `" type="text"></span></p>`;
        }

        $('#dialog-attr-content').html(html);

    },
    delFile(e, field, index) {
        event.stopPropagation();
        event.preventDefault();
        let is_single_file = ['file', 'image'].indexOf(this.field_options[field]['type']) > -1;
        if (is_single_file) {
            this.QE_DATA[field] = '';
        } else {
            this.QE_DATA[field].splice(index, 1);
        }
        this.renderFiles(field);

        return false;
    },
    randomString: function (len) {
        len = len || 32;
        var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
        /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = "";
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    UploadDone(field, res) {

        if (!res.code) {
            this.msg(res.msg, 'error')
            return false;
        }
        console.log('typeof this.QE_DATA[field]', typeof this.QE_DATA[field], this.QE_DATA[field]);

        if (this.QE_DATA[field]) {

            if (typeof this.QE_DATA[field] == "string") {
                this.QE_DATA[field] = [{ 'path': this.QE_DATA[field] }]
            }

        } else {
            this.QE_DATA[field] = [];
        }


        if (['files', 'images', 'attr_files'].indexOf(this.field_options[field]['type']) > -1) {
            delete res.data['ext'];
            delete res.data['md5'];
            delete res.data['size'];
            res.data['hash'] = this.randomString(16);
            this.QE_DATA[field].push(res.data)
        }
        // else if (this.field_options[field]['type'] == 'file') {
        //     this.QE_DATA[field] = res.data;
        // }

        else {
            this.QE_DATA[field] = res.data.path;
        }
        this.renderFiles(field);

    },
    initObject() {
        for (var i in this.field_options) {
            if (typeof this.QE_DATA[i] == "undefined") {
                this.QE_DATA[i] = '';
            }
        }
    },
    QE_SAVE() {
        var data = this.cloneObj(this.QE_DATA), _this = this;
        data['qeditor_table'] = this.table;
        data['qeditor_mode'] = this.mode;
        console.log(data)

        this.ajax(this.option.save_url, data, (res) => {

            if (res.data && !_this.QE_DATA[_this.pk]) {
                _this.QE_DATA[_this.pk] = res.data;
            }

            if (res.code == 200) {
                window.parent && window.parent.postMessage('QE_SAVE_SUCCESS', parent.location.origin)
            } else {
                window.parent && window.parent.postMessage('QE_SAVE_FAIL', parent.location.origin)
            }

            if ($('#QEditor-dialog').length) {
                $('#QEditor-dialog').hide();
            }
        })
    },
    QE_RESET() {
        for (var field in this.QE_DATA) {
            if (field == this.pk) continue;
            this.QE_DATA[field] = '';

            if (typeof this.field_options[field] != "undefined" && ['file', 'files', 'image', 'images',].indexOf(this.field_options[field].type) > -1) {
                console.log(this.field_options[field].type, field)
                this.renderFiles(field);
            }
        }

        if ($('#QEditor-dialog').length) {
            $('#QEditor-dialog').hide();
        }
    },
    selectedOption(field, item) {
        let option = this.field_options[field].option_value,
            value = this.QE_DATA[field],
            type = this.field_options[field].type;
        item = item.toString();

        if (type == "checkbox") {
            if (!value) {
                value = new Array();
                value.push(item.toString())
            } else {

                if (typeof value != "object") {
                    value = [value.toString()];
                }

                if (value.indexOf(item) > -1) {
                    value = this.removeItem(value, item.toString())
                } else {
                    value.push(item.toString())
                }
            }

            this.QE_DATA[field] = value;
        } else {
            //单个选项
            this.QE_DATA[field] = item;
            value = [item.toString()]
        }

        //重新渲染dom
        var option_html = '';

        for (var i in option) {
            //indexof 无效
            var flag = false;
            for (var k in value) {
                if (value[k] == i) {
                    flag = true;
                    break;
                }
            }

            option_html += '<span onclick="QEditor.selectedOption(\'' + field + '\',\'' + i + '\')" class="quiker-edit-option ' + ((value && flag) ? ' QEditor-selected' : '') + '">' + option[i] + '</span> ';
        }

        $('#field-' + field + '-options').html(option_html);

        // console.log(field,item,JSON.stringify(option),value,type)
    },
    getSelect() {
        let _this = this;

        if (!this.picker_key) return false;

        this.ajax(this.option.relation_url, {
            qeditor_keyword: this.picker_key,
            qeditor_table: this.table,
            qeditor_field: this.picker_field,
            qeditor_mode: this.mode
        }, (res) => {
            if (res.data) {
                _this.picker_items = res.data.data;
                _this.picker_config = res.data.config;
            }
            _this.rendPicker();
        })
    },
    show_not_picker() {
        $('.show_picker_dialog,[data-show="!is_picker"]').show();
        $('[data-show="is_picker"]').hide();
        $('.show_picker_dialog .weui-cell__hd').hide();
    },
    show_picker() {
        this.is_picker = true;

        $('#piker-dialog,[data-show="is_picker"]').show();
        $('[data-show="!is_picker"]').hide();
    },
    rendPicker() {

        let html = '';

        if (!this.picker_items || this.picker_items.length < 1) {
            $('#picker-content').html('<p class="text-center text-gray pd-20">-  暂无内容  -</p>');
            return false;
        }

        console.log('this.picker_items', this.picker_items)

        for (var i in this.picker_items) {
            var item = this.picker_items[i];
            html += '<div class="picker-item" onclick="QEditor.picker(this)" data-val=' + JSON.stringify(item) + '>';

            for (var j in this.picker_config['search_fields']) {

                html += '<p><span class="field-name">' + this.picker_config['field_map'][this.picker_config['search_fields'][j]] + ' : </span><span class="field-val">' + this.point(item[this.picker_config['search_fields'][j]], this.picker_key) + '</span></p>'
            }
            html += '</div>';
        }

        $('#picker-content').html(html);
    },

    picker(el) {

        var data = $(el).data('val'), show_name = '';
        if (data) {
            for (var j in this.picker_config['show_field']) {
                show_name += data[this.picker_config['show_field'][j]] + '   ';
            }
            this.QE_DATA[this.picker_field] = data[this.picker_config['val_field']];

            $('#relation-' + this.picker_field + '-text').val(show_name);

            $('#piker-dialog').hide();
        }
    },
    picker_items: [],
    picker_config: {},
    picker_key: '',
    show_picker_dialog: false,
    picker_field: '',
    is_picker: false,
    relationPicker(field, e) {
        console.log(field, e);
        if (this.picker_field != field) {
            this.picker_field = field;
            this.picker_items = [];
            this.picker_config = {};
            this.picker_key = '';
        }
        this.show_picker();
        this.rendPicker();
        setTimeout(() => {
            $('#picker-search').focus();
        }, 100);
    },
    initDom(target) {
        $(target).html('');
        let html = '<div  id="QEditor">', _this = this;
        console.log(this.edit_fields)
        for (var i of this.edit_fields) {
            html += '<!--' + this.field_titles[i] + '-->';
            var method = (typeof Fields[this.field_options[i].type] == "undefined") ? 'text' : this.field_options[i].type,
                mini = this.mini_fields.indexOf(i) > -1;
            html += Fields[method](this.table, i, this.field_options[i], this.field_titles, this.QE_DATA, this.option, this.QE_RELATION, mini);
        }
        html += `<div class="weui-half-screen-dialog__btn-area savearea">
                    <span onclick="QEditor.QE_RESET()" class="weui-btn weui-btn_default" >取消</span>
                    <span onclick="QEditor.QE_SAVE()" class="weui-btn weui-btn_primary" >保存</span>
                  </div>`;
        html += `<div id="piker-dialog" class="show_picker_dialog" style="display: none">
                  <div class="weui-mask" onclick="QEditor.show_picker_dialog=!QEditor.show_picker_dialog"></div>
                  <div class="weui-half-screen-dialog">
                      <div class="weui-half-screen-dialog__hd">
                        <div class="weui-half-screen-dialog__hd__side">
                            <button onclick="QEditor.hidePickerDialog()" class="weui-icon-btn">关闭<i class="weui-icon-close-thin"></i></button>
                        </div>
                        <div class="weui-half-screen-dialog__hd__main">
                          <strong class="weui-half-screen-dialog__title">
                                <span data-show="!is_picker">属性编辑</span>
                                <input data-show="is_picker" type="text" onchange="QEditor.picker_key=this.value" placeholder="输入关键字进行筛选" @input="QEditor.getSelect()" id="picker-search">
                          </strong>
                          <span class="right attr-save" data-show="!is_picker" onclick="QEditor.hidePickerDialog()">保存</span>
                        </div>
                      </div>
                      <div class="weui-half-screen-dialog__bd" data-show="!is_picker" id="dialog-attr-content"> 
                            
                      </div>
                      <div class="weui-half-screen-dialog__bd" data-show="is_picker" id="picker-content">
                            <p class="text-center pd-20">请输入关键字进行筛选</p>
                      </div>
                  </div>
              </div>`;
        html += '</div>';

        $(target).html(html);


    },
    ajax: function (url, data, callback, processData, dataType) {

        let _this = this, handle = typeof processData != "undefined" ? processData : true,

            type = typeof data != "object" ? "get" : "post";


        var api_url = this.option['api_url'] || this.url(), _url;

        if (url.indexOf("http") < 0) {
            _url = api_url + url;
        } else {
            _url = url;
        }

        dataType = dataType ? dataType : 'json';
        _url = _url.replace(/\/{3,}/gi, "/");
        callback = (typeof callback == "undefined" && typeof data == "function") ? data : callback;


        var option = {
            url: _url,
            xhrFields: {
                withCredentials: true
            },
            data: data,
            dataType: dataType,
            type: type,
            processData: handle,
            // async: false,
            success: function (response, status, xhr) {
                if (
                    response &&
                    typeof response.msg != "undefined" &&
                    response.msg
                ) {
                    let type =
                        response.code !== 200
                            ? "error"
                            : "success";
                    _this.msg(response.msg, type);
                }
                if (_this.isCallback(callback)) {
                    callback(response);
                }
            },
            fail: function (res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败:' + res.statusText, 'error');
            },
            error(res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败,请确认服务器地址' + '是否正确', 'error');
            }
        };

        if (typeof processData === false) {
            option.contentType = false;
        }

        $.ajax(option);
    },
    require(js, callback) {

        var jses = typeof js == "string" ? [js] : js, _this = this;

        for (var i in jses) {

            var _js = jses[i],
                _js_ = typeof window['QEDITOR__CONF'] != "undefined" && typeof window['QEDITOR__CONF']['STATIC_MAP'][_js] != "undefined" ?
                    window['QEDITOR__CONF']['STATIC_MAP'][_js] : '';


            if (_js_ && _js_.indexOf('./') > -1) {
                _js_ = this.url() + (_js_.replace('./', ''));
            }

            if (_js_ && typeof window[_js] == "undefined") {

                _js_ && this.loadScript(_js_, function (params) {

                    if (typeof window[_js] == "undefined") {
                        window[_js] = 1;
                    }

                    if (params.index == params.length - 1) {
                        if (_this.isCallback(callback)) {
                            callback();
                        }
                    }
                }, { index: i, length: jses.length, js: _js_ });

            } else {
                // console.log(i, jses.length - 1, i === jses.length - 1, _js_)
                if (Number(i) === jses.length - 1) {
                    if (_this.isCallback(callback)) {
                        callback();
                    }
                }
            }
        }
    },
    address_field: '',
    getLocation(field) {
        this.address_field = field;
        let _this = this;

        $(".field-debug-" + field).text('');

        getCurrentLngLat().then(res => {
            console.log(res, _this.field_options[field]);

            if (!res.data.longitude) {
                return _this.msg('定位失败:' + res.message + ',请确认是否开启HTTPS', 'error');
            } else {

                if (typeof _this.field_options[field]['option_value'].latitude != 'undefined') {
                    QEditor.QE_DATA[_this.field_options[field]['option_value'].latitude] = res.data.latitude;
                    $('#field-' + _this.field_options[field]['option_value'].latitude).val(res.data.latitude);
                }

                if (typeof _this.field_options[field]['option_value'].all != 'undefined') {
                    QEditor.QE_DATA[_this.field_options[field]['option_value'].all] = JSON.stringify({ latitude: res.data.latitude, longitude: res.data.longitude });
                    $('#field-' + _this.field_options[field]['option_value'].all).val(JSON.stringify({ latitude: res.data.latitude, longitude: res.data.longitude }));
                }

                if (typeof _this.field_options[field]['option_value'].longitude != 'undefined') {
                    QEditor.QE_DATA[_this.field_options[field]['option_value'].longitude] = res.data.longitude;
                    $('#field-' + _this.field_options[field]['option_value'].longitude).val(res.data.longitude);
                }
            }

            var params = { latitude: res.data.latitude, longitude: res.data.longitude, type: 'T' };

            inverseGeocoding(params).then(res => {

                if (res.code !== 200) {
                    return _this.msg('定位失败:' + res.message + ',请确认是否开启HTTPS', 'error');
                }
                var data = res.data,
                    address_str = data.addressComponent.province + data.addressComponent.city + data.addressComponent.district + '-' + data.formattedAddress;

                QEditor.QE_DATA[QEditor.address_field] = address_str;

                $("#field-" + QEditor.address_field).val(address_str);

                // $(".field-debug-" + field).text(JSON.stringify(data));


            }).catch(res => {

                // getLocationByIp().then(res => {
                //
                //     var params = {latitude: res.result.location.lat, longitude: res.result.location.lng, type: 'T'};
                //
                //     inverseGeocoding(params).then(res => {
                //         $(".field-debug-" + field).text(JSON.stringify(res));
                //     })
                // })

                return _this.msg('定位失败:' + res.message + ',是否开启HTTPS', 'error');
                // $("#field-" + QEditor.address_field).val(loc.poiaddress + loc.poiname);
                // QEditor.QE_DATA[QEditor.address_field] = loc.poiaddress + loc.poiname;
                // var target = QEditor.field_options[QEditor.address_field].option_value;
                //
                // console.log(target, typeof QEditor.QE_DATA[target] != "undefined");
                //
                // if (target && typeof QEditor.QE_DATA[target] != "undefined") {
                //     QEditor.QE_DATA[target] = loc;
                // }

            });
        })


    },
    removeItem: function (arr, val) {
        return arr.filter(function (i) {
            return i !== val;
        })
    },
    formatDate: function (time, fmt, is_date) {
        if (is_date) {
            var date = new Date(time);
        } else {
            var _time = time.toString(),
                timeStr =
                    _time.length === 10
                        ? parseInt(_time) * 1000
                        : parseInt(_time),
                date = new Date(timeStr);
        }
        var _fmt = fmt ? fmt : "yyyy-MM-dd hh:mm:ss";
        if (/(y+)/.test(_fmt)) {
            _fmt = _fmt.replace(
                RegExp.$1,
                (date.getFullYear() + "").substr(4 - RegExp.$1.length)
            );
        }
        let o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
        };
        // 遍历这个对象
        for (let k in o) {
            if (new RegExp(`(${k})`).test(_fmt)) {
                let str = o[k] + "";
                _fmt = _fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length === 1
                        ? str
                        : ("00" + str).substr(str.length)
                );
            }
        }
        //let date=new Date(fmt);
        return _fmt;
    },
    msg: function (msg, type, callback) {
        let _this = this;
        if (typeof weui != "undefined") {
            weui.toast(msg, {
                duration: 2000,
                extClass: type == 'error' ? 'weui-icon-warn' : 'weui-icon-success-no-circle',
                callback: function () {
                    _this.isCallback(callback) && callback();
                }
            });

            return;
        }

        if (typeof UIkit != "undefined") {
            UIkit.notification({ message: msg, status: type == 'success' ? 'success' : 'error' });
            _this.isCallback(callback) && callback();
            return;
        }

        alert(msg);
    },
    cloneObj: function (obj) {
        let str,
            newobj = obj.constructor === Array ? [] : {};
        if (typeof obj !== "object") {
            return;
        } else if (window.JSON) {
            (str = JSON.stringify(obj)), //系列化对象
                (newobj = JSON.parse(str)); //还原
        } else {
            for (let i in obj) {
                newobj[i] =
                    typeof obj[i] === "object" ? cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    },
    async loadScript(url, callback, params) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (typeof (callback) != "undefined") {
            if (script.readyState) {
                script.onreadystatechange = function () {
                    if (script.readyState == "loaded" || script.readyState == "complete") {
                        script.onreadystatechange = null;
                        callback(params);
                    }
                };
            } else {
                script.onload = function () {
                    callback(params);
                };
            }
        }
        script.src = url;
        document.head.appendChild(script);
    },
    isCallback: function (callback) {
        return typeof callback == "function";
    },
    init_tinymce(target, option) {
        let _this = this;
        this.require('editor_lang', function () {
            tinymce.init({
                selector: '.QE_DATA_EDITOR',
                plugins: 'image media  preview lists ',
                toolbar: ['undo redo preview removeformat  image   forecolor bold italic underline strikethrough', '  backcolor align  bullist numlist outdent indent  fontfamily fontsize'],
                //  https://www.tiny.cloud/docs/tinymce/6/full-featured-open-source-demo/
                language: 'zh-Hans',
                menubar: false,
                inline: true,
                paste_data_images: true,
                promotion: false,
                convert_urls: false,
                file_picker_types: 'image',
                init_instance_callback: function (editor) {
                    editor.on('Change', function (e) {
                        _this.QE_DATA[target] = editor.getContent();
                    });
                },
                images_upload_handler: file_upload_handler
            });
        })
    }, point(str, key) {
 
        var reg = new RegExp((`(${key})`), "gi"),
            replace = '<span style="color:#FD463E;font-weight:bold;">$1</span>';
        return str?str.replace(reg, replace):'';
    },
    area_code: '',
    area_create: false,
    selectArea(field, code) {
        console.log('selectArea', code, field)
        if (typeof code != "undefined") {
            this.area_code = code;
        }
        this.initArea(field);
    },

    dialogArea(field, create) {
        this.attr_field = field;
        this.attr_has_save = false;
        this.area_create = true;
        $('#dialog-attr-content').html(`<div id="position-` + field + `" class="area-value"></div>  <div class="weui-cell__bd" id="field-` + field + `-options"></div>`);
        this.initArea(field);
        $('#piker-dialog .weui-half-screen-dialog__title').text(this.field_titles[field]);
        this.show_not_picker();
    },
    miniValue(field, change) {
        var html = '', options = this.field_options[field]['option_value'] || {};
        console.log('mini', this.field_options[field].type, field)
        switch (this.field_options[field].type) {
            case 'radio':
                html = this.field_titles[field] + ' : ' + options[this.QE_DATA[field]];
                break;
            case 'checkbox':
                var value = '',
                    values = typeof this.QE_DATA[field] == "string" ? this.QE_DATA[field].split(',') : this.QE_DATA[field];
                for (var i in values) {
                    value += options[values[i]] + ' ' || ' ';
                }
                html = this.field_titles[field] + ' : ' + value;

                break;
            case 'area':
                this.ajax('?qeditor=miniValue', {
                    type: this.field_options[field].type,
                    table: this.table,
                    field: field,
                    value: this.QE_DATA[field]
                }, (res) => {

                    if (typeof change == "undefined") {
                        $('[data-single-area-field="' + field + '"]').val(res.data);
                        return;
                    }
                    html = this.field_titles[field] + ' : ' + res.data;
                    $('.qedit-mini-field[data-field="' + field + '"]').html(html);
                })
                return '';
                break;

            default:
                html = this.field_titles[field] + ' ' + this.QE_DATA[field];
                break;
        }
        console.log(html, this.QE_DATA[field], this.field_options[field].type);

        if (typeof change != "undefined") {
            return $('.qedit-mini-field[data-field="' + field + '"]').html(html);
        }
        return html;
    },
    initArea(field) {
        this.area_code = this.area_code || (typeof this.QE_DATA[field] != "object" ? this.QE_DATA[field] : (this.QE_DATA[field] ? this.QE_DATA[field][0] : ''));

        let _this = this, position = this.area_code;

        if (typeof _this.field_options[field]['option_value']['default'] != "undefined" && !position) {
            position = _this.field_options[field]['option_value']['default'];
        }

        this.ajax('?qeditor=area', { position: position }, (res) => {

            var html = '', option = _this.field_options[field]['option_value'];

            if (res.data.level) {
                var levels = res['data'].level;
                for (var i in levels) {
                    if (option && typeof option['show'] != "undefined" && Number(i) < option['show']) {
                        continue;
                    }
                    html += '<span onclick="QEditor.selectArea(\'' + field + '\',' + levels[i].code + ')" class="address-level ' + ((levels[i].code == res['data']['self'].code) ? 'bg-color' : '') + '">' + levels[i].name + '</span> ';
                }
                $('#position-' + field).html(html);
            }

            if (res.data.parents) {
                var html = '', levels = res['data'].sons || res['data'].parents;


                if (typeof res.data.self.level != "undefined" && res.data.self.level < "5") {
                    html += '<span onclick="QEditor.selectArea(\'' + field + '\',' + (res.data.self.pcode || 0) + ')" class="quiker-edit-option bg-red">上一级</span> ';
                }

                for (var i in levels) {
                    html += '<span onclick="QEditor.selectArea(\'' + field + '\',' + levels[i].code + ')" class="quiker-edit-option ' + ((levels[i].code == res['data']['self'].code) ? 'bg-color' : '') + '">' + levels[i].name + '</span> ';
                }
                console.log(html, '#field-' + field + '-options');
                $('#field-' + field + '-options').html(html);

            }

        })
    },
    /**
     *
     * @param url
     * @returns {{path: string, protocol: string, file: string | string, port: string, query: string, host: string, source, params: {}, hash: string, relative: string | string, segments: string[]}}
     */
    parseURL(url) {
        let a = document.createElement("a");
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(":", ""),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function () {
                let ret = {},
                    seg = a.search.replace(/^\?/, "").split("&"),
                    len = seg.length,
                    i = 0,
                    s;
                for (; i < len; i++) {
                    if (!seg[i]) {
                        continue;
                    }
                    s = seg[i].split("=");
                    ret[s[0]] = s[1];
                }
                return ret;
            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ""])[1],
            hash: a.hash.replace("#", ""),
            path: a.pathname.replace(/^([^\/])/, "/$1"),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ""])[1],
            segments: a.pathname.replace(/^\//, "").split("/"),
        };
    }

}


